package controller

import (
	"github.com/labstack/echo"
	"github.com/sirupsen/logrus"
	"gopkg.in/mgo.v2/bson"
	"net/http"
	"src/config"
	"src/controller/param"
	"src/model"
	"src/util/context"
	"src/util/log"
	"strconv"
)

var replyLogger = log.GetLogger()

func writereplyLoggerLoggerLog(funcName, errMsg string, err error) {
	replyLogger.WithFields(logrus.Fields{
		"package":  config.LogMessage,
		"file":     "reply.go",
		"function": funcName,
		"err":      err,
	}).Warn(errMsg)
}

func CreatReply(c echo.Context) error {
	reply := model.Reply{}
	err := c.Bind(&reply)
	if err != nil {
		writereplyLoggerLoggerLog("CreatReply", config.ErrorMsgParamWrong, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}
	if reply.Text == "" {
		writereplyLoggerLoggerLog("CreatReply", config.ErrorContent, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorContent)
	}

	flag, err := model.PostWeixinMsgSecCheck(reply.Text)
	if flag == false {
		writereplyLoggerLoggerLog("CreatReply", "内容违规1", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, "内容违规")
	}
	if err != nil {
		writereplyLoggerLoggerLog("CreatReply", "内容违规2", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, "内容违规")
	}

	id := context.GetJWTUserOpenid(c)
	reply.UserID = id

	reply, err = model.CreateReply(reply)
	if err != nil {
		writereplyLoggerLoggerLog("CreatReply", config.ErrorReplyCreat, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorReplyCreat)
	}

	//创建消息
	if reply.ReplyUserID != reply.UserID {
		M := model.Message{}
		if reply.Level == 2 {
			M.Type = 14
		} else {
			M.Type = 18
		}
		M.ForumPostId = reply.ForumPostId
		M.Anonymity = reply.Anonymity
		M.UserID = reply.ReplyUserID
		M.ContentId = reply.ReplyID
		M.ActionContentId = reply.ID.Hex()
		M.ActionUserId = reply.UserID
		err = model.CreatMessage(M)
		if err != nil {
			writereplyLoggerLoggerLog("CreatReply", config.ErrorMessageCreat, err)
			return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMessageCreat)
		}
	}

	err = model.UpdateCommentReply(reply.TopicID, 1)
	if err != nil {
		writereplyLoggerLoggerLog("CreatReply", config.ErrorUpdateCommentReply, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateCommentReply)
	}

	err = model.UpdateForumpostReply(reply.ForumPostId, 1)
	if err != nil {
		writereplyLoggerLoggerLog("CreatReply", config.ErrorUpdateForumpostReply, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateForumpostReply+err.Error())
	}

	err = model.UpdateForumpostScore(reply.ForumPostId, config.ReplyScore)
	if err != nil {
		writereplyLoggerLoggerLog("CreatReply", config.ErrorUpdateForumpostScore, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateForumpostScore)
	}

	err = model.UpdateCommentScore(reply.TopicID, config.ReplyScore)
	if err != nil {
		writereplyLoggerLoggerLog("CreatReply", config.ErrorUpdateCommentScore, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateCommentScore)
	}

	resData := map[string]interface{}{}
	resData["replie"] = reply

	return context.RetData(c, resData)
}

func DeleteReply(c echo.Context) error {
	id := param.Id{}
	err := c.Bind(&id)
	if err != nil {
		writereplyLoggerLoggerLog("DeleteReply", config.ErrorMsgParamWrong, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}

	reply := model.Reply{}
	userid := context.GetJWTUserOpenid(c)
	reply.UserID = userid
	reply.ID = bson.ObjectIdHex(id.Id)

	reply, err = model.DeleteReply(reply.ID.Hex(), reply.UserID, false)
	if err != nil {
		writereplyLoggerLoggerLog("DeleteReply", config.ErrorReplyDelete, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorReplyDelete)
	}
	//query := bson.M{
	//	"content_id":id.Id,
	//}
	//_ = model.DeleteMessageAll(query)

	err = model.UpdateCommentReply(reply.TopicID, -1)
	if err != nil {
		writereplyLoggerLoggerLog("DeleteReply", config.ErrorUpdateCommentReply, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateCommentReply)
	}
	err = model.UpdateForumpostReply(reply.ForumPostId, -1)
	if err != nil {
		writereplyLoggerLoggerLog("DeleteReply", config.ErrorUpdateForumpostReply, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateForumpostReply)
	}

	r := []model.Reply{}
	r, err = model.GetReplyByReplyALL(reply.ID.Hex())
	for i := 0; i < len(r); i++ {
		//query := bson.M{
		//	"content_id":r[i].ID.Hex(),
		//}
		//_ = model.DeleteMessageAll(query)
		_, _ = model.DeleteReply(r[i].ID.Hex(), r[i].UserID, true)
	}

	err = model.UpdateForumpostScore(reply.ForumPostId, -config.ReplyScore)
	if err != nil {
		writereplyLoggerLoggerLog("DeleteReply", config.ErrorUpdateForumpostScore, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateForumpostScore)
	}
	err = model.UpdateCommentScore(reply.TopicID, -config.ReplyScore)
	if err != nil {
		writereplyLoggerLoggerLog("DeleteReply", config.ErrorUpdateCommentScore, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateCommentScore)
	}

	//删除消息
	if reply.ReplyUserID != reply.UserID {
		m := model.Message{}
		if reply.TopicID == reply.ReplyID {
			m.Type = 14
		} else {
			m.Type = 18
		}
		m.UserID = reply.ReplyUserID
		m.ContentId = reply.ReplyID
		m.ActionUserId = reply.UserID
		m.ActionContentId = reply.ID.Hex()
		err = model.DeleteMessage(m)
		if err != nil {
			writecommentLoggerLoggerLog("DeleteComment", config.ErrorMessageDelete, err)
			return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMessageDelete)
		}
	}

	return context.RetData(c, "")
}

func GetRepliesByComment(c echo.Context) error {
	reply := param.GetReply{}
	var err error
	reply.Page, err = strconv.Atoi(c.QueryParam("page"))
	reply.PerPage, err = strconv.Atoi(c.QueryParam("per_page"))
	reply.CommentId = c.QueryParam("comment_id")
	if err != nil || reply.PerPage <= 0 || reply.Page == 0 || reply.CommentId == "" {
		writereplyLoggerLoggerLog("GetRepliesByComment", config.ErrorMsgParamWrong, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}

	resData := map[string]interface{}{}
	resData["replies"], err = model.GetReplyByComment(reply.CommentId, reply.Page, reply.PerPage, "")
	if err != nil {
		writereplyLoggerLoggerLog("GetRepliesByComment", config.ErrorReplyGet, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorReplyGet)
	}

	return context.RetData(c, resData)
}

func GetReplyByForumpost(c echo.Context) error {
	reply := param.GetReply{}
	var err error
	reply.Page, err = strconv.Atoi(c.QueryParam("page"))
	reply.PerPage, err = strconv.Atoi(c.QueryParam("per_page"))
	reply.Postid = c.QueryParam("post_id")
	if err != nil || reply.PerPage <= 0 || reply.Page == 0 || reply.Postid == "" {
		writereplyLoggerLoggerLog("GetRepliesByForumpost", config.ErrorMsgParamWrong, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}
	resData := map[string]interface{}{}
	resData["replies"], err = model.GetReplyByForumpost(reply.Postid, reply.Page, reply.PerPage)
	if err != nil {
		writereplyLoggerLoggerLog("GetRepliesByComment", config.ErrorReplyGet, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorReplyGet)
	}
	return context.RetData(c, resData)

}

func GetReplyById(c echo.Context) error {
	id := param.Id{}
	id.Id = c.QueryParam("id")
	var err error
	if id.Id == "" {
		writereplyLoggerLoggerLog("GetReplyById", config.ErrorMsgParamWrong, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}
	resData := map[string]interface{}{}
	resData["Reply"], err = model.GetReplyByid(id.Id)
	if err != nil {
		writereplyLoggerLoggerLog("GetReplyById", config.ErrorReplyGet, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorReplyGet)
	}
	return context.RetData(c, resData)
}
